package com.speedy.course.ui

import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.speedy.course.R
import com.speedy.course.base.BaseActivity
import com.speedy.course.databinding.ActivityAddLessonBinding
import com.speedy.course.databinding.ActivityAddTaskBinding
import com.speedy.course.db.entity.Task
import com.speedy.course.vm.TaskViewModel
import kotlinx.coroutines.launch

class AddTaskActivity : BaseActivity() {

    private val viewModel: TaskViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val viewBinding = ActivityAddTaskBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)

        viewBinding.apply {
            title.ivPublicBack.setOnClickListener {
                finish()
            }
            title.rightTitle.setOnClickListener {
                val task = viewBinding.task
                if(task == null || task.content.isNullOrBlank()){
                    showToast("请先添加比较内容")
                }else{
                    viewModel.saveOrUpdateTask(task){
                        finish()
                    }
                }

            }
        }

        lifecycleScope.launch {
            viewModel.taskStateFlow.collect{
                viewBinding.task = it
            }
        }

        val id = intent.getIntExtra("id",-1)

        lifecycleScope.launch {
            val task = viewModel.queryTaskByID(id)?: Task()
            viewBinding.task = task
        }

    }
}